var express = require("express");
var router = express.Router();
//const mysql = require('mysql');
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const configs = require("../config");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
// 动态路由处理器
const mysql = require("mysql2/promise");

// 创建数据库连接池
const pool = mysql.createPool({
  host: configs.mysql.host,
  user: configs.mysql.user,
  password: configs.mysql.password,
  database: configs.mysql.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});
// 确保日志目录存在
const logsDir = path.join(__dirname, "../log");
if (!fs.existsSync(logsDir)) {
  fs.mkdirSync(logsDir, { recursive: true });
}

const logToFile = (message) => {
  const logFilePath = path.join(__dirname, "../log/api.log"); // 您的日志文件路径
  fs.appendFile(logFilePath, message, (err) => {
    if (err) {
      console.error("Logging to file failed", err);
    }
  });
};

// 创建日志消息并调用logToFile函数
const logAPICall = (req, res, error = null) => {
  const now = new Date().toISOString();
  const method = req.method;
  const url = req.originalUrl;
  const requestBody = JSON.stringify(req.body);
  const responseStatus = res.statusCode;
  const responseBody = JSON.stringify(res.locals.responseBody || null);
  const errorMessage = error ? error.message : "";

  const logEntry = `${now} - Method: ${method}, URL: ${url}, Request Body: ${requestBody}, Response Status: ${responseStatus}, Response Body: ${responseBody}, Error: ${errorMessage}\n`;

  logToFile(logEntry);
};
router.all("/api/:table/:id?", async (req, res) => {
  try {
    //const database = req.params.db;
    const table = req.params.table;
    let query = "";
    const id = req.params.id;

    switch (req.method) {
      case "GET":
        query = id
          ? `SELECT * FROM ${table} WHERE id = ${id}`
          : `SELECT * FROM ${table}`;
        break;
      case "POST":
        
        query = `INSERT INTO ${table} SET ?`;
        break;
      case "PUT":
        query = `UPDATE ${table} SET ? WHERE id = ${id}`;
        break;
      case "DELETE":
        query = `DELETE FROM ${table} WHERE id = ${id}`;
        break;
    }

    if (req.method === "GET" || req.method === "DELETE") {
      const [result] = await pool.execute(query);
      res.json({
        status: "操作成功",
        code: 200,
        data: result,
      });
    } else {
      // console.log('req.body',req.body.city)
      // let values = [];
      // for (let key in req.body) {
      //   if (req.body.hasOwnProperty(key)) {

      //     values.push(req.body[key]);
      //   }
      // }
      // console.log('values',values)
      //const [result] = await pool.execute(query,[req.body]);
      const data = req.body;
      const [result] = await pool.query(query, data);

      res.json({
        status: "操作成功",
        code: 200,
        data: result,
      });
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error:"+JSON.stringify(err) });
    logAPICall(req, res, err); // 记录带有错误信息的日志
    return;
  }
  logAPICall(req, res); // 记录正常的API调用日志
});
router.get("/api-curd/:table", async (req, res) => {
  try {
    const table = req.params.table;
    const query = `SELECT * FROM ${table}`;
    const [result] = await pool.execute(query);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error" });
    logAPICall(req, res, err);
  }
});
router.get("/api-curd/:table/:id", async (req, res) => {
  try {
    const table = req.params.table;
    const id = req.params.id;
    const query = `SELECT * FROM ${table} WHERE id = ${id}`;
    const [result] = await pool.execute(query);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error" });
    logAPICall(req, res, err);
  }
});
router.post("/apis/:table/:where", async (req, res) => {
  try {
    const table = req.params.table;
    const where = req.params.where;
    const query = `SELECT * FROM ${table} WHERE ${where}`;
    const [result] = await pool.execute(query);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error" });
    logAPICall(req, res, err);
  }
});
router.post("/api-curd/:table", async (req, res) => {
  try {
    const table = req.params.table;
    const query = `INSERT INTO ${table} SET ?`;
    const data = req.body;
    const [result] = await pool.query(query, data);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error" });
    logAPICall(req, res, err);
  }
});
router.put("/api-curd/:table/:id", async (req, res) => {
  try {
    const table = req.params.table;
    const id = req.params.id;
    const query = `UPDATE ${table} SET ? WHERE id = ${id}`;
    const data = req.body;
    const [result] = await pool.query(query, data);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error" });
    logAPICall(req, res, err);
  }
});
router.delete("/api-curd/:table/:id", async (req, res) => {
  try {
    const table = req.params.table;
    const id = req.params.id;
    const query = `DELETE FROM ${table} WHERE id = ${id}`;
    const [result] = await pool.execute(query);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error" });
    logAPICall(req, res, err);
  }
});
// 万能代理接口路由
router.post("/proxy", async (req, res) => {
  try {
    // 从请求中提取相关信息
    const { url, method, headers, data } = req.body;

    // 构建axios请求的配置对象
    const config = {
      method: method.toUpperCase(),
      url: url,
      headers: headers,
      data: data,
    };
    // 记录请求发送的时间戳
    const startTime = new Date();
    // 使用axios发送请求到目标URL
    const response = await axios.request(config);
    const endTime = new Date();
    const responseTime = endTime - startTime;

    // 将响应时间添加到响应数据中
    response.data.responseTime = responseTime;
    // 将响应数据返回给客户端
    // 构建自定义响应对象
    const responseObject = {
      statusCode: response.status, // 状态码
      data: response.data, // 实际数据
      responseTime: responseTime, // 响应时间
    };

    // 将自定义响应对象返回给客户端
    res.json(responseObject);
  } catch (error) {
    // 错误处理
    console.error("Proxy error:", error);

    // 计算错误处理时间
    const responseTime = new Date() - startTime;

    // 构建错误响应对象
    const errorResponse = {
      statusCode: res.statusCode, // 状态码（默认为500）
      data: error.message, // 错误信息
      responseTime: responseTime, // 响应时间
    };

    // 记录API调用日志
    logAPICall(req, res, errorResponse);

    // 将错误响应对象返回给客户端
    res.status(500).json(errorResponse);
  }
});
// POST路由，接收SQL查询语句
router.post('/query', async (req, res) => {
  try {
    const data = req.body;
    const [result] = await pool.execute(data.sql);
    res.json({
      status: "操作成功",
      code: 200,
      data: result,
    });
    logAPICall(req, res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal Server Error:"+JSON.stringify(err) });
    logAPICall(req, res, err);
  }
});
// router.all("/api/:table/where", async (req, res) => {
//   try {
//     const table = req.params.table;
//     const wheredata = req.body;
//   } catch (err) {
//     console.error(err);
//     res.status(500).json({ message: "Internal Server Error" });
//     logAPICall(req, res, err); // 记录带有错误信息的日志
//     return;
//   }
//   logAPICall(req, res); // 记录正常的API调用日志
// });

module.exports = router;
